package com.emm.yixun.website.controller.workflow.online.his;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricProcessInstanceQuery;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.emm.yixun.anotations.MerchantResourcesConfig;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.DateStyle;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.system.service.UserServiceFacade;
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.mybatis.Page;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.entity.workflow.process.HistoricProcessInstanceVo;
import com.emm.yixun.website.service.ActivitiProcessServiceImpl;
import com.emm.yixun.website.vo.TaskQueryVo;
/**
 * 在线结束任务
 */
@Controller
@RequestMapping(value = "/backstage/workflow/online/his/")
public class HisController extends BaseController<Object>{

	private static final String SECURITY_URL="/backstage/workflow/online/his/index";
	 @Autowired
	 private HistoryService historyService;
	 
	 @Autowired
	 private RepositoryService repositoryService;
	 
	 @Autowired
	 private UserServiceFacade userServiceFacade;
	 
	 @Autowired
	 private ActivitiProcessServiceImpl activitiProcessServiceImpl;
    /**
     * 任务列表
     */
    @RequestMapping(value = "index")
    @MerchantResourcesConfig(resourcesCode="menu_0010_0002")
    public String index(HttpServletRequest request, HttpServletResponse response, org.springframework.ui.Model model) {
    	if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){	
    		model.addAttribute("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));
			return "/system/workflow/online/his/list";
		}
		return Const.NO_AUTHORIZED_URL;
    }
 
    @RequestMapping(value = "findByPage", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes findByPage(Page<HistoricProcessInstanceVo> page,TaskQueryVo taskQueryVo) {
    	AjaxRes ar=getAjaxRes();
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_MENU, SECURITY_URL))) {
			try {
				int pageNum=PageUtil.begin(page.getPageNum(), page.getPageSize());
				int pageSize=page.getPageSize();
				List<HistoricProcessInstanceVo> vos=new ArrayList<HistoricProcessInstanceVo>();
				User user=ShiroUtil.getCurrentUser();		
				// 根据当前人的ID查询
				HistoricProcessInstanceQuery query=historyService.createHistoricProcessInstanceQuery().startedBy(user.getUserAccount());
				if(StringUtils.isNotBlank(taskQueryVo.getProcessInstanceKey())){
					query=query.processDefinitionKey(taskQueryVo.getProcessInstanceKey());
				}
				//状态
				String taskStatus=taskQueryVo.getTaskStatus();
				if(StringUtils.isNotBlank(taskStatus)){
					if(taskStatus.equals("0")){
						//运行中
						query=query.unfinished();
					}else if(taskStatus.equals("1")){
						//已结束
						query=query.finished();
					}
				}
		        //发起日期
		        if(StringUtils.isNotBlank(taskQueryVo.getStartTimeStart())){
		        	String createdAfter=taskQueryVo.getStartTimeStart()+" 00:00:00";
		        	query=query.startedAfter(DateUtils.StringToDate(createdAfter, DateStyle.YYYY_MM_DD_HH_MM_SS));
		        	
		        }
	            if(StringUtils.isNotBlank(taskQueryVo.getStartTimeEnd())){
	            	String createdBefore=taskQueryVo.getStartTimeEnd()+" 23:59:59";
	            	query=query.startedBefore(DateUtils.StringToDate(createdBefore, DateStyle.YYYY_MM_DD_HH_MM_SS));
		        }
	            //结束日期
	            if(StringUtils.isNotBlank(taskQueryVo.getEndTimeStart())){
	            	String completedAfter=taskQueryVo.getEndTimeStart()+" 00:00:00";
	            	query=query.finishedAfter(DateUtils.StringToDate(completedAfter, DateStyle.YYYY_MM_DD_HH_MM_SS));
	            }
	            
	            if(StringUtils.isNotBlank(taskQueryVo.getEndTimeEnd())){
	            	String completedBefore=taskQueryVo.getEndTimeEnd()+" 23:59:59";
	            	query=query.finishedBefore(DateUtils.StringToDate(completedBefore, DateStyle.YYYY_MM_DD_HH_MM_SS));
	            }
				
				List<HistoricProcessInstance> list=query.orderByProcessInstanceStartTime().desc().listPage(pageNum, pageSize);
				for(HistoricProcessInstance t:list){	
					HistoricProcessInstanceVo vo=new HistoricProcessInstanceVo(t.getId(),t.getProcessDefinitionId(),
							t.getStartTime(),t.getEndTime(),t.getDeleteReason());	
					
					ProcessDefinition processDefinition=repositoryService.createProcessDefinitionQuery().processDefinitionId(t.getProcessDefinitionId()).singleResult();
					vo.setBusinessKey(t.getBusinessKey());
					vo.setProcInstName(processDefinition.getName());
					String procInstStatusName="运行中";
					if(null!=t.getEndTime()){
						procInstStatusName="已结束";
					}
					vo.setProcInstStatusName(procInstStatusName);
					String startUserName="";
					UserDto ud=new UserDto();
					ud.setUserAccount(t.getStartUserId());
					ResponseList<User> userList=userServiceFacade.findByDto(ud);
					if(userList.isSuccess() && null!=userList.getEntity()){
						startUserName=userList.getEntity().get(0).getUserName();
					}
					String formKey=activitiProcessServiceImpl.getFormKey(t.getProcessDefinitionId())+"?id="+t.getBusinessKey();
					vo.setFormKey(formKey);
					vo.setStartUserName(startUserName);
					vos.add(vo);
				}
		        long count=query.count();    
				page.setTotalRecord((int) count);
				page.setResults(vos);			
				Map<String, Object> p=new HashMap<String, Object>();
				p.put("permitBtn",getPermitBtn(Const.RESOURCES_TYPE_BUTTON));
				p.put("list",page);		
				ar.setSucceed(p);
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
		}
		return ar;
	}
}
